package service

import (
	"server/internal/model"
	"time"
)

func (svc *Service) NewCourse(name, description, chainName, chainAccount, username string, start, end int) error {
	c := &model.Course{
		Name:         name,
		Description:  description,
		ChainName:    chainName,
		ChainAccount: chainAccount,
		Username:     username,
		Start:        start,
		End:          end,
	}

	return c.Create(svc.engine)
}

func (svc *Service) GetMyCourses(username string) ([]map[string]interface{}, error) {
	c := &model.Course{
		Username: username,
	}
	courses, err := c.GetMy(svc.engine)
	if err != nil {
		return nil, err
	}

	len := len(courses)
	courseArr := make([]map[string]interface{}, len)
	for i := 0; i < len; i++ {
		courseArr[i] = make(map[string]interface{})
		courseArr[i]["id"] = courses[i].ID
		courseArr[i]["name"] = courses[i].Name
		courseArr[i]["description"] = courses[i].Description
		courseArr[i]["chainName"] = courses[i].ChainName
		courseArr[i]["chainAccount"] = courses[i].ChainAccount
		courseArr[i]["start"] = time.Unix(int64(courses[i].Start), 0).Format("2006-01-02 15:04:05")
		courseArr[i]["end"] = time.Unix(int64(courses[i].End), 0).Format("2006-01-02 15:04:05")
	}

	return courseArr, nil
}

func (svc *Service) GetCurrentCourses() ([]map[string]interface{}, error) {
	c := &model.Course{}
	courses, err := c.GetCurrent(svc.engine)
	if err != nil {
		return nil, err
	}

	len := len(courses)
	courseArr := make([]map[string]interface{}, len)
	for i := 0; i < len; i++ {
		courseArr[i] = make(map[string]interface{})
		courseArr[i]["id"] = courses[i].ID
		courseArr[i]["name"] = courses[i].Name
		courseArr[i]["description"] = courses[i].Description
		courseArr[i]["chainName"] = courses[i].ChainName
		courseArr[i]["chainAccount"] = courses[i].ChainAccount
		courseArr[i]["start"] = time.Unix(int64(courses[i].Start), 0).Format("2006-01-02 15:04:05")
		courseArr[i]["end"] = time.Unix(int64(courses[i].End), 0).Format("2006-01-02 15:04:05")
	}

	return courseArr, nil
}

func (svc *Service) DeleteCourse(id int) error {
	c := &model.Course{}
	return c.Delete(svc.engine, id)
}
